package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Alert;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class AutoTestUtils {

    public static WebDriver driver;
    public WebDriverWait webDriverWait = null;



    public AutoTestUtils(String url){
        driver = createDriver();
        driver.get(url);
        webDriverWait = new WebDriverWait(driver, Duration.ofSeconds(3));
    }

    private static WebDriver createDriver() {
        if (driver == null) {
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");
            driver = new ChromeDriver(options);

            //添加隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }

    public void getScreenShot(String str) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        //./src/test/image/2024-10-24/test2-21175422.png
        String fileName = "./src/test/image/" + dirTime + "/" + str + "-" + fileTime + ".png";
        File file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        FileUtils.copyFile(file, new File(fileName));
    }

    /**
     * 未登录状态是否弹窗
     * @param
     */
    public  void noLoginPage(){
        webDriverWait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        alert.accept();
        webDriverWait.until(ExpectedConditions.urlToBe("http://120.26.160.116:8080/blog_login.html"));
    }
}
